package com.ms.education.handler;

import cn.dev33.satoken.same.SaSameUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * <p>Project:education-FeignInterceptor
 * <p>Powered by ms on 2023-03-12 20:42:03
 * <p>
 * 服务内部嗲用鉴权
 *
 * @author ms
 * @version 1.0
 * @since 1.8
 */
@Component
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        requestTemplate.header(SaSameUtil.SAME_TOKEN, SaSameUtil.getToken());
        //如果调用方有token,则加入请求头
        ServletRequestAttributes srat = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = srat.getRequest().getHeader("token");
        if (!StringUtils.isEmpty(token)) {
            requestTemplate.header("token", token);
        }

    }
}
